const marked = require('marked')

const { writeQuestion, findOne, find } = require('../models/question')

const question = async (req, res, next) => {
    res.set('content-type', 'application/json; charset=utf-8')
    const {username,
        title,
        avatar,
        content,
        time_limit,
        memory_limit,
        cases,} = req.body

    const result = await writeQuestion(username,
        title,
        avatar,
        content,
        time_limit,
        memory_limit,
        cases,)

    if(result) {
        console.log(result)
        res.render('succ', {
            data: JSON.stringify({
                id: result._id
            })
        })
    }
}

const questionDetail = async (req, res, next) => {
    const id = req.params.id

    const blog = await findOne(id)

    if(blog) {
        const {username,
            id,
            title,
            content,
            avatar,
            time_limit,
            memory_limit,
            cases,
            publish_date,} = blog
        let html

        await marked(content, function (err, data) {
            if(err) throw err
            html = data
        })

        res.render('succ', {
            data: JSON.stringify({
                username,
                id,
                title,
                avatar,
                html,
                time_limit,
                memory_limit,
                cases,
                publish_date,
            })
        })
    }

}

const questionList = async (req, res, next) => {

    const numPer = 10

    res.set('content-type', 'application/json; charset=utf-8')
    const num = req.params.num
    const questions = await find()

    const ret_questions = questions.slice(num * numPer, (num + 1) * numPer)

    console.log(ret_questions, num * numPer, )

    res.render('succ', {
        data: JSON.stringify(ret_questions)
    })
}

const questionNumbers = async (req, res, next) => {

    res.set('content-type', 'application/json; charset=utf-8')
    const questions = await find()

    res.render('succ', {
        data: JSON.stringify({
            "numbers": questions.length
        })
    })
}

module.exports = {
    question,
    questionDetail,
    questionList,
    questionNumbers,
}